package com.yupi.project.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.google.gson.Gson;
import com.mdd.model.entity.InterfaceInfo;
import com.yupi.project.annotation.AuthCheck;
import com.yupi.project.common.BaseResponse;
import com.yupi.project.common.ErrorCode;
import com.yupi.project.common.ResultUtils;
import com.yupi.project.constant.UserConstant;
import com.yupi.project.exception.ThrowUtils;
import com.yupi.project.mapper.UserInterfaceInfoMapper;
import com.yupi.project.model.vo.InterfaceInfoVo;
import com.yupi.project.service.InterfaceInfoService;
import org.springframework.beans.BeanUtils;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.ZSetOperations;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

import static com.yupi.project.scheduled.SchedulingTask.INTERFACE_INVOKE_TOP_KEY;

/**
 * 分析数据接口
 * @author Mdd
 * @Github <a href="https://github.com/mdd123cc"/>
 * @Gitee <a href="https://gitee.com/mdd115192"/>
 */
@RestController
@RequestMapping("/analysis")
public class AnalyseController {

    @Resource
    private UserInterfaceInfoMapper userInterfaceInfoMapper;

    @Resource
    private InterfaceInfoService interfaceInfoService;

    @Resource
    private StringRedisTemplate stringRedisTemplate;

    /**
     * 获取接口调用top
     * @return
     */
    @GetMapping("/top/interface/invoke")
    @AuthCheck(mustRole = UserConstant.ADMIN_ROLE)
    public BaseResponse<List<InterfaceInfoVo>> getInterfaceTopByInvoke(){
        //从redis中获取排行榜信息
        ZSetOperations<String, String> zSetOperations = stringRedisTemplate.opsForZSet();
        Set<String> resSet = zSetOperations.reverseRange(INTERFACE_INVOKE_TOP_KEY, 0, 3);
        ThrowUtils.throwIf(resSet==null, ErrorCode.SYSTEM_ERROR,"redis中无数据");
        Gson gson = new Gson();
        //获取前limit个调用最多的接口
        List<InterfaceInfoVo> interfaceInfoVos = resSet.stream().map(res -> {
            return gson.fromJson(res, InterfaceInfoVo.class);
        }).collect(Collectors.toList());
        return ResultUtils.success(interfaceInfoVos);
    }
}
